#include "buzzer.h"

PWM_Config_t PWM_Config = {
    .duty_cycle = 50,
    .freq = 0,
};

void Buzz_Init(void)  //由PWM驱动
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | BUZZER_CLK, ENABLE);
    
    GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
	GPIO_InitStructure.GPIO_Pin = BUZZER_PIN;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(BUZZER_PORT, &GPIO_InitStructure);
    
    TIM_InternalClockConfig(TIM4);
    
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInitStructure.TIM_Period = 0;               //ARR
	TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1;		//PSC
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure);
    
    TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_OCStructInit(&TIM_OCInitStructure);
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = 0;
    
	TIM_OC4Init(TIM4, &TIM_OCInitStructure);
    TIM_OC4PreloadConfig(TIM4,TIM_OCPreload_Enable);// OC1预装载寄存器使能//CH1 TIM1
    
	TIM_Cmd(TIM4, ENABLE);
}

void PWM_SetConfig(void)
{
    uint8_t arr_val;
    if(PWM_Config.freq) arr_val = 1000000 / PWM_Config.freq;
    TIM_SetAutoreload(TIM4, arr_val);
    TIM_SetCompare4(TIM4, arr_val * PWM_Config.duty_cycle / 100);
}

void PWM_SetFreq(uint16_t freq)
{
    PWM_Config.freq = freq;
    PWM_SetConfig();
}

void PWM_DutyCycleSet(uint8_t val)
{
    if(val  > 100)  val = 100;
    PWM_Config.duty_cycle = val;
    PWM_SetConfig();
}
